package top.haijunit.bucket.server.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.haijunit.mark.common.core.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * @Author 百旺张
 * @Date 2021/11/13
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/")
public class DemoController {
    //public static final String PAYMENT_URL = "http://localhost:8001";
    // 此处写的是服务名称，可自动实现负载均衡
    public static final String PAYMENT_URL = "http://SERVER-PROVIDER-01";

    @Value("${server.port}")
    private String serverPort;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/")
    public Result<JSONObject> demo(HttpServletRequest request) {
        return Result.ok(JSONUtil.createObj(), "访问成功").addData("port", serverPort).addData("uri", request.getRequestURI());
    }

    @GetMapping("/discovery")
    public Result<JSONObject> discovery() {
        List<JSONObject> list = new ArrayList<>();
        for (String name : discoveryClient.getServices()) {
            List<ServiceInstance> instances = discoveryClient.getInstances(name);
            for (ServiceInstance instance : instances) {
                list.add(JSONUtil.createObj().set("host", instance.getHost()).set("port", instance.getPort()).set("uri", instance.getUri()).set("serviceId", instance.getServiceId()).set("instanceId", instance.getInstanceId()));
            }
        }
        return Result.ok(JSONUtil.createObj(), "访问成功").addData("port", serverPort).addData("discovery", discoveryClient.getServices()).addData("service", list).addData("UUID", UUID.randomUUID());
    }


    @GetMapping("/rest")
    public Result user(HttpServletRequest request) {
        return restTemplate.getForObject(PAYMENT_URL + "/", Result.class);
    }
}
